package com.xph.core.common.json;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.log4j.Logger;

public class UrlDecorator
{
	private Logger logger = Logger.getLogger(UrlDecorator.class);
    private StringBuffer url = null;
    
    public UrlDecorator(String urlString) {
    	this.url = null;
        this.url = new StringBuffer(urlString);
    }
    
    /**
     * 将参数拼装在url问号前面
     * @param param
     * @return
     */
    public UrlDecorator append(String paramValue) {
        if (paramValue != null && !"".equals(paramValue)) {
            int i = this.url.indexOf("?");
            if(i >= 0) {
                this.url.insert(i, paramValue + "/");
            } else {
                this.url.append(paramValue).append("/");
            }
        }else{
        	logger.error("当前url"+this.toString()+", appendValue:"+paramValue);
        	throw new RuntimeException("错误：URL路径中出现空字符串或者null对象");
        }
        return this;
    }
    
    /**
     * 让append方法支持int参数
     * 
     * @param paramValue
     * @return
     */
    public UrlDecorator append(int paramValue) {
        return this.append("" + paramValue);
    }
    
    /**
     * 支持int整理参数拼装
     * 
     * @param paramName
     * @param paramValue
     * @return
     */
    public UrlDecorator add(String paramName, int paramValue) {
        return this.add(paramName, ""+paramValue);
    }
    
    /**
     * 将参数拼装在url问号后面
     * @param paramName
     * @param paramValue
     * @return
     */
    public UrlDecorator add(String paramName, String paramValue) {
        if (this.url.indexOf("?") <= 0) {
            this.url.append("?");
        }
        if (paramValue != null && !"".equals(paramValue)) {
            if (!this.url.toString().endsWith("?")) {
                this.url.append("&");
            }
            this.url.append(paramName).append("=").append(encode(paramValue));
        }
        return this;
    }
    
    //URI不允许有空格等字符，如果参数值有空格，需要此方法转换
    private String encode(String str){
    	try {
			return URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			//针对不支持的编码时报错，utf-8应该是支持的
			logger.warn("参数转码异常", e);
			throw new RuntimeException(e);
		}
    }

    public String toString() {
        return this.url.toString();
    }
    
    public StringBuffer getUrl()
    {
        return url;
    }

    public void setUrl(StringBuffer url)
    {
        this.url = url;
    }

    
}
